﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Common;
using HIWSystem.Models;
using System.ComponentModel.DataAnnotations;
using System.Windows;

namespace HIWSystem.ViewModel
{
    public class EmployeeMenuManageViewModel : ViewModelBase
    {
        #region 属性
        private Regex regex = null;
        private readonly string pattern = @"^[A-Z]{2}(\|[A-Z]{2})*$";//菜单权限匹配模式

        private bool isFirstFilterUserNo=true;

        private ObservableCollection<EmployeesEntity> backupEmployees;

        private ObservableCollection<EmployeesEntity> userNos;
        /// <summary>
        ///  员工实体数据集
        /// </summary>
        public ObservableCollection<EmployeesEntity> UserNos
        {
            get { return userNos; }
            set { userNos = value; this.RaisePropertyChanged(() => UserNos); }
        }
        private EmployeesEntity selectedUserNo;
        /// <summary>
        /// 选择的员工实体
        /// </summary>
        public EmployeesEntity SelectedUserNo
        {
            get { return selectedUserNo; }
            set { selectedUserNo = value; this.RaisePropertyChanged(() => SelectedUserNo); }
        }
        private string userNo;
        /// <summary>
        /// 选择的工号
        /// </summary>
        public string UserNo
        {
            get { return userNo; }
            set { userNo = value; this.RaisePropertyChanged(() => UserNo); }
        }
        private string searchUserNoText;
        /// <summary>
        /// 员工下拉文本框中输入的搜索内容
        /// </summary>
        public string SearchUserNoText
        {
            get { return searchUserNoText; }
            set { searchUserNoText = value; this.RaisePropertyChanged(() => SearchUserNoText); }
        }
        private bool isOpenComboUserNoDropDown;
        /// <summary>
        ///是否打开员工下拉文本块
        /// </summary>
        public bool IsOpenComboUserNoDropDown
        {
            get { return isOpenComboUserNoDropDown; }
            set { isOpenComboUserNoDropDown = value; this.RaisePropertyChanged(() => IsOpenComboUserNoDropDown); }
        }
        private string nameCn="";
        /// <summary>
        /// 中文名
        /// </summary>
        public string NameCn
        {
            get { return nameCn; }
            set { nameCn = value; this.RaisePropertyChanged(() => NameCn); }
        }
        private string nameEn="";
        /// <summary>
        /// 英文名
        /// </summary>
        public string NameEn
        {
            get { return nameEn; }
            set { nameEn = value; this.RaisePropertyChanged(() => NameEn); }
        }
        private string menuAccess="";
        /// <summary>
        /// 菜单权限
        /// </summary>
        public string MenuAccess
        {
            get { return menuAccess; }
            set { menuAccess = value; this.RaisePropertyChanged(() => MenuAccess); }
        }
        private ObservableCollection<MenuEntity> menuConfigs;
        /// <summary>
        /// 菜单配置信息
        /// </summary>
        public ObservableCollection<MenuEntity> MenuConfigs
        {
            get { return menuConfigs; }
            set { menuConfigs = value; this.RaisePropertyChanged(() => MenuConfigs); }
        }
        #endregion

        #region 命令
        private RelayCommand filterUserNoCmd;
     
        public RelayCommand FilterUserNoCmd
        {
            get 
            {
                if (filterUserNoCmd==null)
                {
                    filterUserNoCmd = new RelayCommand(FilterUserNo);
                }
                return filterUserNoCmd; 
            }
            set { filterUserNoCmd = value; }
        }
        private RelayCommand loadedPageCmd;

        public RelayCommand LoadedPageCmd
        {
            get 
            {
                if (loadedPageCmd==null)
                {
                    loadedPageCmd = new RelayCommand(LoadedPage);
                }
                return loadedPageCmd;
            }
            set { loadedPageCmd = value; }
        }
        private RelayCommand<MenuEntity> dataGridMouseDoubleCmd;

        public RelayCommand<MenuEntity> DataGridMouseDoubleCmd
        {
            get 
            {
                if (dataGridMouseDoubleCmd==null)
                {
                    dataGridMouseDoubleCmd = new RelayCommand<MenuEntity>(DataGridMouseDoubleHandler);
                }
                return dataGridMouseDoubleCmd; 
            }
            set { dataGridMouseDoubleCmd = value; }
        }
        private RelayCommand<string> comboUserNo_SelectionChangedCmd;

        public RelayCommand<string> ComboUserNo_SelectionChangedCmd
        {
            get 
            {
                if (comboUserNo_SelectionChangedCmd==null)
                {
                    comboUserNo_SelectionChangedCmd = new RelayCommand<string>(ComboUserNo_SelectionChangedHandler);
                }
                return comboUserNo_SelectionChangedCmd; 
            }
            set { comboUserNo_SelectionChangedCmd = value; }
        }
        private RelayCommand addCmd;

        public RelayCommand AddCmd
        {
            get 
            {
                if (addCmd==null)
                {
                    addCmd = new RelayCommand(AddEmployeeMenuAccess);
                }
                return addCmd; 
            }
            set { addCmd = value; }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadedPage()
        {
            this.FillUserNoToComboBox();
            this.FillMenuConfigToDataGrid();
        }
        /// <summary>
        /// 添加员工菜单权限
        /// </summary>
        private void AddEmployeeMenuAccess()
        {
            if (this.UserNo=="" || this.NameCn=="")
            {
                MessageBox.Show("工号、中文名、英文名不能为空.","软件温馨提示",MessageBoxButton.OK,MessageBoxImage.Error);
                return;
            }
            if (this.MenuAccess=="")
            {
                MessageBox.Show("权限不能为空！", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (!MenuAccessFormatIsValid(this.MenuAccess))
            {
                MessageBox.Show("菜单权限文本框中内容格式不正确,正确格式是【AB或者AB|AC|AD】.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            EmployeesEntity employeesEntity = new EmployeesEntity { UserNo=this.UserNo,NameCn=this.NameCn,NameEn=this.NameEn,Access=this.MenuAccess};
            if (BusinessProcess.ManageEmployeeMenuAccess(employeesEntity))
            {
                MessageBox.Show("添加成功,为了应用权限请重新登录.", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("添加失败！", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// 填充员工信息到下拉列表框中
        /// </summary>
        private void FillUserNoToComboBox()
        {
            DataTable dtEmployees = new DataTable();
            dtEmployees = BusinessProcess.GetUserInfo("*");
            UserNos = new ObservableCollection<EmployeesEntity>();
            for (int i = 0; i < dtEmployees.Rows.Count; i++)
            {
                UserNos.Add(new EmployeesEntity
                {
                    UserNo = dtEmployees.Rows[i]["UserNo"].ToString(),
                    NameCn= dtEmployees.Rows[i]["NameCn"].ToString(),
                    NameEn= dtEmployees.Rows[i]["NameEn"].ToString(),
                    Access= dtEmployees.Rows[i]["Access"].ToString()
                });
            }
        }
        /// <summary>
        /// 填充菜单配置到数据网格中
        /// </summary>
        private void FillMenuConfigToDataGrid()
        {
            DataTable dtMenuConfig = new DataTable();
            dtMenuConfig = BusinessProcess.GetMenuLevelInfo();
            MenuConfigs = new ObservableCollection<MenuEntity>();
            for (int i = 0; i < dtMenuConfig.Rows.Count; i++)
            {
                MenuConfigs.Add(new MenuEntity
                {
                    MenuCn = dtMenuConfig.Rows[i]["MenuCn"].ToString(),
                    MenuEn = dtMenuConfig.Rows[i]["MenuEn"].ToString(),
                    MenuAccess = dtMenuConfig.Rows[i]["ActorLevel"].ToString()
                }); ;
            }
        }
        /// <summary>
        /// 过滤员工信息
        /// </summary>
        private void FilterUserNo()
        {

            IsOpenComboUserNoDropDown = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (isFirstFilterUserNo)
            {
                backupEmployees = new ObservableCollection<EmployeesEntity>();
                backupEmployees = UserNos;
                isFirstFilterUserNo = false;
            }
            if (!string.IsNullOrEmpty(SearchUserNoText))
            {
                IEnumerable<EmployeesEntity> employeesEntities = UserNos.Where(s => s.UserNo.ToUpper().Contains(SearchUserNoText.ToUpper()));
                UserNos = new ObservableCollection<EmployeesEntity>();
                foreach (var e in employeesEntities)
                {
                    UserNos.Add(e);
                }
            }
            else
            {
                UserNos = backupEmployees;
            }

        }
        /// <summary>
        /// 数据网格鼠标双击事件
        /// </summary>
        private void DataGridMouseDoubleHandler(MenuEntity menuEntity)
        {
            //测试使用
            //MessageBox.Show(menuEntity.MenuCn + menuEntity.MenuEn + menuEntity.MenuAccess);
            if (MenuAccessFormatIsValid(MenuAccess))
            {
                if (!MenuAccess.Contains(menuEntity.MenuAccess))
                {
                    MenuAccess += "|" + menuEntity.MenuAccess;
                }
                else
                {
                    MessageBox.Show("员工已经包含权限【"+ menuEntity.MenuAccess + "】", "软件温馨提示", MessageBoxButton.OK, MessageBoxImage.Hand);
                }
            }
            else
            {
                MessageBox.Show("菜单权限文本框中内容格式不正确,正确格式是【AB或者AB|AC|AD】.","软件温馨提示",MessageBoxButton.OK,MessageBoxImage.Error);
            }
            
            

        }
        private bool MenuAccessFormatIsValid(string menuAccess)
        {
            regex = new Regex(pattern);
            return regex.IsMatch(menuAccess);
        }
        /// <summary>
        /// 用户下拉框选择改变事件
        /// </summary>
        private void ComboUserNo_SelectionChangedHandler(string obj)
        {
            //解决TabControl和ComboBox的SelectionChanged冲突问题
            if (obj==null)
            {
                return;
            }
            EmployeesEntity employeesEntity = UserNos.First(x => x.UserNo == obj);
            this.NameCn = employeesEntity.NameCn;
            this.NameEn = employeesEntity.NameEn;
            this.MenuAccess = employeesEntity.Access;
        }

        #endregion
    }
}
